<template>
  <div class="app">
    <div class="container">
      <div class="sider">
        <side-bar-com></side-bar-com>
      </div>
      <div class="main">
        <header-com @clearHistory="conversation = []"></header-com>

        <!-- 聊天框 -->
        <main-com :conversation="conversation"></main-com>
        <!-- 提问框 -->
        <div class="footer">
          <form ref="form" class="question-form" @submit.prevent="handleSubmit">
            <textarea
              rows="1"
              ref="input"
              class="question-input"
              :disabled="isQuestioning"
              autocomplete="off"
              type="text"
              v-model="userQst"
              placeholder="请输入您的问题"
            />
            <button v-if="!isQuestioning" type="submit">提交</button>
            <button v-else @click="pause">取消</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import headerCom from "@/components/HeaderCom.vue";
import mainCom from "@/components/MainCom.vue";
import sideBarCom from "@/components/sideBarCom.vue";

export default {
  data() {
    return {
      userQst: "",
      conversation: [],
      isQuestioning: false,
      eventSource: null,
    };
  },
  components: {
    headerCom,
    mainCom,
    sideBarCom,
  },
  methods: {
    pause() {
      if (this.eventSource) {
        this.eventSource.close();
      }
      this.handleResponseEnd();
    },
    async handleSubmit() {
      if (this.userQst.trim() !== "") {
        this.conversation.push({ role: "user", content: this.userQst });
        this.startStream(this.userQst);
        this.userQst = "";
      }
    },
    startStream(message) {
      this.isQuestioning = true;

      this.eventSource = new EventSource(
        `http://47.97.49.128:59539/stream?message=${encodeURIComponent(
          message
        )}`
      );
      let aiResponse = "";

      this.eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (aiResponse === "") {
          this.conversation.push({ role: "assistant", content: data.text });
        } else {
          this.conversation[this.conversation.length - 1].content += data.text;
        }
        aiResponse += data.text;
      };

      this.eventSource.onerror = (event) => {
        console.error("Error:", event);
        this.eventSource.close();
        this.handleResponseEnd();
      };

      this.eventSource.addEventListener("close", () => {
        this.eventSource.close();
        this.handleResponseEnd();
      });
    },
    handleResponseEnd() {
      this.getHistory();
      this.isQuestioning = false;
      if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
      }
    },
    getHistory() {
      fetch("http://47.97.49.128:59539/history")
        .then((response) => response.json())
        .then((data) => {
          this.conversation = data;
        });
    },
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  mounted() {
    this.getHistory();
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  line-height: 1.5;
}
p {
  margin-bottom: 10px;
}
.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.3rem 0.8rem;
  background-color: #2f2f2f;
  color: #b4b4b4;
}
.code-header button {
  background-color: #2f2f2f;
  border: none;
  outline: none;
  color: #b4b4b4;
}
.hljs {
  border-radius: 0.5em;
}
.hljs .code {
  overflow-y: auto;
  padding: 1rem;
}
.hljs .code-header {
  border-radius: 0.5em 0.5em 0 0;
}

/* 序号右移 */
.hljs ol {
  overflow: auto;
}
.hljs code ol li {
  width: 100%;
  margin-left: 0.1em;
  line-height: 0.8em;
  list-style-type: none;
  counter-increment: line;
}

.hljs ol li:before {
  content: counter(line);
  display: inline-block;
  width: 2em;
  color: #999;
  text-align: right;
  font-size: 14px;
  font-weight: bold;
}
.hljs ol li .code {
  /* 自动换行 */
  overflow-y: auto;
  padding-left: 2em;
}

.response ol li {
  margin-left: 2em;
  line-height: 2.5em;
}
.response ul li {
  margin-left: 2em;
  line-height: 2.5em;
}
</style>

<style scoped>
.container {
  display: flex;
}
.main {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  font-family: Arial, sans-serif;
  color: #333;
}

.footer {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.question-form {
  display: flex;
  align-items: center;
  height: 60px;
  width: 100%;
  max-width: 800px;
  background-color: #f4f4f4;
  padding: 10px;
  border-radius: 30px;
}

textarea[type="text"] {
  resize: none;
  overflow: auto;
  background-color: #f4f4f4;
  flex: 1;
  font: 16px;
  padding: 8px;
  border: none;
  outline: none;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
}

button {
  background-color: #f4f4f4;
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  outline: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
@media screen and (max-width: 768px) {
  .sider {
    display: none;
  }
}
</style>